package com.qubuyer.business.home.activity

import android.os.Bundle
import android.os.Vibrator
import android.text.TextUtils
import cn.bingoogolapple.qrcode.core.QRCodeView
import com.qubuyer.R
import com.qubuyer.business.auth.view.RegisterActivity
import com.qubuyer.core.app.DataBindingActivity
import com.qubuyer.databinding.ActivityScanBinding
import com.qubuyer.utils.NavigationUtil

/**
 * @author Susong
 * @date 创建时间2019/4/10
 * @description 扫一扫activity
 */
class ScanActivity : DataBindingActivity<ActivityScanBinding>(), QRCodeView.Delegate {

    override fun onDataBind(dataBinding: ActivityScanBinding) {
        dataBinding.host = this
    }

    override val layoutId: Int
        get() = R.layout.activity_scan

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        dataBinding.titleBar.setOnNaviClick { finish() }
        dataBinding.zbarview.setDelegate(this)
    }

    override fun onStart() {
        super.onStart()
        dataBinding.zbarview.startCamera()
        dataBinding.zbarview.startSpotAndShowRect()
    }

    override fun onStop() {
        dataBinding.zbarview.stopCamera()
        super.onStop()
    }

    override fun onDestroy() {
        dataBinding.zbarview.onDestroy() // 销毁二维码扫描控件
        super.onDestroy()
    }

    override fun onScanQRCodeSuccess(result: String) {
        val vibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator
        vibrator.vibrate(200)
        if (!TextUtils.isEmpty(result)) {
            NavigationUtil.forward(this, RegisterActivity::class.java, result)
        }
    }

    override fun onCameraAmbientBrightnessChanged(isDark: Boolean) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        var tipText = dataBinding.zbarview.scanBoxView.tipText
        val ambientBrightnessTip = "\n环境过暗，请打开闪光灯"
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                dataBinding.zbarview.scanBoxView.tipText = tipText + ambientBrightnessTip
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip))
                dataBinding.zbarview.scanBoxView.tipText = tipText
            }
        }
    }

    override fun onScanQRCodeOpenCameraError() {
        toast("打开相机出错")
    }
}